package com.huike.springboot1.demos.security;

import com.huike.springboot1.demos.pojo.Permission;
import com.huike.springboot1.demos.pojo.Role;
import com.huike.springboot1.demos.pojo.User1;
import com.huike.springboot1.demos.service.User1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Lazy
    @Autowired
    private User1Service userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        User1 user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 查询用户角色和权限
        User1 userWithRoles = userService.findUserWithRoles(user.getId());

        // 封装权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (userWithRoles.getRoles() != null && !userWithRoles.getRoles().isEmpty()) {
            for (Role role : userWithRoles.getRoles()) {
                // 添加角色
                authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));

                // 添加权限
                if (role.getPermissions() != null && !role.getPermissions().isEmpty()) {
                    for (Permission permission : role.getPermissions()) {
                        authorities.add(new SimpleGrantedAuthority(permission.getPermissionCode()));
                    }
                }
            }
        }
        System.out.println(">>> 用户 " + username + " 拥有权限：" + authorities);
        // 返回Spring Security需要的UserDetails对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1, // 是否启用
                true, // 账号是否未过期
                true, // 凭证是否未过期
                true, // 账号是否未锁定
                authorities
        );
    }
}
